#include "servicecode/HttpResponse.h"
#include "Mylogger.hh"
#include <sstream>
#include <fstream>

using std::ifstream;
using std::ostringstream;

HttpResponse::HttpResponse()
{
    _headers["Content-Type"] = "text/html; charset=UTF-8";
    _headers["Server"] = "EchoServer/1.0";
}

void HttpResponse::set_html_body(const string &htmlpath)
{
    ifstream ifs(htmlpath);
    if (!ifs.is_open())
    {
        LogError("打开 %s 失败", htmlpath.c_str());
    }
    // 将文件所有内容放入_body中
    string buffer((std::istreambuf_iterator<char>(ifs)),
                  std::istreambuf_iterator<char>());
    _body = buffer;

    // 将报文体的长度放入报文头
    _headers["Content-Length"] = std::to_string(_body.size());
}

void HttpResponse::set_str_body(const string & str)
{
    _body = str;
    // 将报文体的长度放入报文头
    _headers["Content-Length"] = std::to_string(_body.size());
}


// 获得http响应
string HttpResponse::get_html_response()
{
    // 构建响应行
    ostringstream response;
    response << _version << " "
             << _statusCode << " "
             << _statusText << "\r\n";
    // 添加所有头部
    for (const auto &header : _headers)
    {
        response << header.first << ": "
                 << header.second << "\r\n";
    }
    //添加分隔行
    response<<"\r\n";
    // 5. 添加响应正文
    response << _body;
        
    return response.str();
}